<?php

namespace App\Http\Controllers;
use App\Type;
use Illuminate\Http\Request;

class TypeController extends Controller {
	//
	protected $model;

	public function __construct(Type $type) {
		$this->model = $type;
	}

	public function types() {
		return view('types.index');
	}

	public function list() {
		$types = $this->model->all();
		return view('types.list', compact('types'));
	}

	public function store(Request $request) {
		$id = $request->id ?: 0;
		$this->validate($request, [
			'id' => 'sometimes|required|numeric',
			'name' => 'required|unique:types,name,' . $id,
		]);
		if ($id != 0) {
			$model = $this->model->findOrFail($id);
			$model->fill($request->only(['name']));
			$model->save();
		} else {
			$this->model->create($request->only(['name']));
		}
		return json_encode(['code' => 200, 'msg' => 'success']);
	}

	public function create() {
		return view('types.form');
	}

	public function edit(Type $type) {
		return view('types.form', compact('type'));
	}

	public function destroy($id) {
		$this->model->where('id', $id)->delete();
		return ['code' => 200, 'msg' => 'success'];
	}
}
